<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="报告名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入报告名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="报告类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择报告类型"
          clearable
          class="!w-240px"
        >
          <el-option label="舌诊" :value="1" />
          <el-option label="体检报告" :value="2" />
          <el-option label="REPORT" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"> <Icon icon="ep:search" class="mr-5px" /> 搜索 </el-button>
        <el-button @click="resetQuery"> <Icon icon="ep:refresh" class="mr-5px" /> 重置 </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column label="报告编号" align="center" prop="id" width="100" />
      <el-table-column label="报告名称" align="center" prop="name" min-width="120" />
      <el-table-column
        label="报告总结"
        align="center"
        prop="summary"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报告类型" align="center" prop="type" width="100">
        <template #default="scope">
          <el-tag :type="getReportTypeTagType(scope.row?.type)">
            {{ getReportTypeText(scope.row?.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleView(scope.row)"> 查看 </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 舌诊报告弹窗 -->
  <Modal
    v-model:visible="tongueReportVisible"
    title=""
    :show-close="true"
    :close-on-click-modal="false"
    custom-class="tongue-report-modal"
  >
    <TongueReport v-if="tongueReportVisible" :report-data="tongueReportData" />
  </Modal>
</template>

<script lang="ts" setup>
import { formatDate } from '@/utils/formatTime'
import * as MemberReportApi from '@/api/member/report'
import Modal from '@/components/Modal/index.vue'
import TongueReport from '@/components/TongueReport/index.vue'

const props = defineProps<{
  userId: number
}>()

const message = useMessage()

const loading = ref(true)
const total = ref(0)
const list = ref<MemberReportApi.MemberReportVO[]>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  type: undefined
})
const queryFormRef = ref()

// 舌诊报告弹窗相关
const tongueReportVisible = ref(false)
const tongueReportData = ref({})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  console.log('开始获取会员报告列表，用户ID:', props.userId)
  try {
    const params: MemberReportApi.MemberReportPageReqVO = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      userId: props.userId
    }

    // 如果有类型筛选，添加type参数
    if (queryParams.type) {
      params.type = queryParams.type
    }

    // 如果有名称筛选，可以在这里添加name参数（如果后端支持）
    // if (queryParams.name) {
    //   params.name = queryParams.name
    // }

    const data = await MemberReportApi.getMemberReportPage(params)

    let resultList = data && data.list && Array.isArray(data.list) ? data.list : []

    // 如果后端不支持按名称筛选，前端进行筛选
    if (queryParams.name) {
      resultList = resultList.filter((item) => item.name && item.name.includes(queryParams.name!))
    }

    list.value = resultList
    total.value = data?.total || 0
  } catch (error) {
    console.error('获取会员报告列表失败:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 显示舌诊报告 */
const showTongueReport = (row: MemberReportApi.MemberReportVO) => {
  try {
    // 解析JSON字符串
    const data = row.report
    let reportData
    if (data.includes('.pdf')) {
      reportData = data.replace(/^"|"$/g, '')
    } else {
      reportData = JSON.parse(data)
    }
    tongueReportData.value = reportData
    tongueReportVisible.value = true
  } catch (error) {
    console.error('解析报告数据失败:', error)
    message.error('报告数据格式错误')
  }
}

/** 查看报告 */
const handleView = (row: MemberReportApi.MemberReportVO) => {
  if (!row || !row.id) {
    message.error('报告数据无效')
    return
  }

  // 判断报告类型
  if (row.type === 1) {
    // 舌诊报告
    showTongueReport(row)
  } else {
    message.info(`查看${row.name || '未知报告'}`)
  }
}

/** 删除报告 */
const handleDelete = async (row: MemberReportApi.MemberReportVO) => {
  if (!row || !row.id) {
    message.error('报告数据无效')
    return
  }
  try {
    await message.delConfirm()
    await MemberReportApi.deleteMemberReport(row.id)
    message.success('删除成功')

    // 重新获取列表数据
    await getList()
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

/** 获取报告类型标签类型 */
const getReportTypeTagType = (type: number | null | undefined) => {
  if (!type) return 'default'
  switch (type) {
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'info'
    default:
      return 'default'
  }
}

/** 获取报告类型文本 */
const getReportTypeText = (type: number | null | undefined) => {
  if (!type) return '未知类型'
  switch (type) {
    case 1:
      return '舌诊'
    case 2:
      return '体检报告'
    case 3:
      return 'REPORT'
    default:
      return '未知类型'
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
// 舌诊报告弹窗样式
:deep(.tongue-report-modal) {
  .el-dialog {
    width: 420px !important;
    max-width: 420px !important;
    height: 80vh;
    max-height: 700px;
    margin: 5vh auto !important;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  }

  .el-dialog__header {
    display: none;
  }

  .el-dialog__body {
    padding: 0;
    height: 100%;
    overflow: hidden;
  }

  .el-dialog__close {
    position: absolute;
    top: 15px;
    right: 15px;
    z-index: 1000;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;

    &:hover {
      background: rgba(0, 0, 0, 0.7);
    }
  }
}

// 手机适配
@media (max-width: 480px) {
  :deep(.tongue-report-modal) {
    .el-dialog {
      width: 95vw !important;
      max-width: 95vw !important;
      height: 90vh;
      margin: 5vh auto !important;
    }
  }
}
</style>
